package org.kingtop.mybatis.binding;

import org.apache.ibatis.binding.BindingException;
import org.apache.ibatis.binding.MapperRegistry;
import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.kingtop.mybatis.mapper.SqlInjector;
import org.kingtop.mybatis.mapper.SqlInjectorFactory;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 该类主要用于注册所有的dao和方法<br>
 * 继承至MapperRegistry<br>
 * 这里修改两个地方，一个是注入SQL语句SqlInjector，另外一个是修改MapperProxyFactory->MybatisMapperProxyFactory
 * </p>
 *
 * @author Caratacus hubin
 * @author 陈金波
 * @since 2017-04-19
 */
public class MybatisMapperRegistry extends MapperRegistry {

	private final Configuration config;
	/** 修改代理，将分页的结果修改*/
	private final Map<Class<?>, MybatisMapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MybatisMapperProxyFactory<?>>();

	private final SqlInjectorFactory sqlInjectorFactory;

	public MybatisMapperRegistry(Configuration config) {
		super(config);
		this.config = config;
		this.sqlInjectorFactory = new SqlInjectorFactory(config);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
		final MybatisMapperProxyFactory<T> mapperProxyFactory = (MybatisMapperProxyFactory<T>) knownMappers.get(type);
		if (mapperProxyFactory == null) {
			throw new BindingException("Type " + type + " is not known to the MybatisPlusMapperRegistry.");
		}
		try {
			return mapperProxyFactory.newInstance(sqlSession);
		} catch (Exception e) {
			throw new BindingException("Error getting mapper instance. Cause: " + e, e);
		}
	}

	@Override
	public <T> boolean hasMapper(Class<T> type) {
		return knownMappers.containsKey(type);
	}

	@Override
	public <T> void addMapper(Class<T> type) {
		if (type.isInterface()) {
			if (hasMapper(type)) {
				return;
				// throw new BindingException("Type " + type +
				// " is already known to the MybatisPlusMapperRegistry.");
			}
			boolean loadCompleted = false;
			try {
				knownMappers.put(type, new MybatisMapperProxyFactory<>(type));
				// It's important that the type is added before the parser is
				// run
				// otherwise the binding may automatically be attempted by the
				// mapper parser. If the type is already known, it won't try.

				MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
				parser.parse();
				// 注入原生的SQL语句
				SqlInjector sqlInjector = this.sqlInjectorFactory.buildSqlInjector(type);
				sqlInjector.injectAllSql();
				loadCompleted = true;
			} finally {
				if (!loadCompleted) {
					knownMappers.remove(type);
				}
			}
		}
	}

	/**
	 * @since 3.2.2
	 */
	@Override
	public Collection<Class<?>> getMappers() {
		return Collections.unmodifiableCollection(knownMappers.keySet());
	}

}
